package com.secret.chain.secretchain.interceptor;

import com.secret.chain.secretchain.context.BaseContext;
import com.secret.chain.secretchain.propreties.JwtProperties;
import com.secret.chain.secretchain.utils.JwtUtil;
import io.jsonwebtoken.Claims;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        try {
            String token = request.getHeader("Authorization");
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Integer id = Integer.valueOf(claims.get("user_id").toString());
            BaseContext.setCurrentId(id);
            System.out.println(BaseContext.getCurrentId());
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
}